import * as React from 'react';
import {Table, Form, Select, Input, Button, Col, Row, Modal, Icon, Popver, Steps, notification } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import axios from 'axios'
import Api from '../../services/apis'

const FormItem = Form.Item;
const Option = Select.Option;
const Step = Steps.Step;

@connect (({user, loading}) => ({
    currentUser: user.currentUser,
    currentUserLoading: loading.effects['user/fetchCurrent']
}))

class BorrowApproval extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            modalVisible: false,
            stepData: [
                {
                title: '申请借档',
                },
                {
                title: '部门领导审核',
                },
                {
                title: '经办部门审核',
                },
                {
                title: '经办人',
                },
                {
                title: '完成'
                }
            ],
            tableData: [],
            current: 1,
            pageSize: 5,
            docIds:''
        }
    }

    
    sendData = () => {
        const that = this;
        const searchValues = this.props.form.getFieldsValue();
        axios.post(Api.rmGetDocList,{
            docName: searchValues.s_name,
            docStatus: searchValues.s_state,
            docType: searchValues.s_type,
            currentPage: this.state.current
        })
        .then((function(resp){
            const data = resp.data;
            if(data.list.length === 0){
                notification.destroy();
                notification['warning']({message:'暂无数据'})
            }else{
                data.list.forEach((d,i) => {
                    d.key = i;
                    d.doc_status1 = d.doc_status === '0' ? "未借出" : parseInt(d.doc_status) < 4 ? '审批中' : "已借出";
                    switch (d.doc_type){
                        case "0":
                            d.doc_type = "核实情况报告";
                        break;
                        case "1":
                            d.doc_type = "内部文档";
                        break;
                        case "2":
                            d.doc_type = "划转通知";
                        break;
                        case "3":
                            d.doc_type = "权属文件";
                        break;
                    }
                });
            }

            that.setState({
                tableData: data.list,
                pageSize: data.pageSize,
                current: data.currentPage,
                totalSize: data.totalSize
            })
        }))
    }

    componentWillMount(){
        this.sendData();
    }

    query = (e) => {
        e.preventDefault();
        /* this.props.form.validateFields((err,values)=>{
            if(!err){
                console.log('value:',values)
            }
        }) */
        this.setState({current:1},()=>{
            this.sendData();
        })
    }

    pageChange = (page) => {
        this.setState({current:page},()=>{
            this.sendData();
        })
    }

    resetForm = () => {
        this.props.form.resetFields();
    }

    setModalVisible = (visible) => {
        this.setState({modalVisible:visible})
    }
    
    openModal = (id,type,status) => {
        this.setState({docIds:id,openModalType:type,docStatus : status})

        //根据ID查询档案信息
        this.getDocById(id);
        //获取档案借款记录
        this.getRecord(id);
    }

    //根据ID查询档案信息
    getDocById = (id) => {
        const that = this;
        axios.post(Api.rmGetDocById,{
            docId:id
        })
        .then(function(resp){
            const data = resp.data;
            that.setModalVisible(true);
            switch (data.doc_type){
                case "0":
                    data.doc_type = "核实情况报告";
                break;
                case "1":
                    data.doc_type = "内部文档";
                break;
                case "2":
                    data.doc_type = "划转通知";
                break;
                case "3":
                    data.doc_type = "权属文件";
                break;
            }
            that.setState({
                m_number: data.ref_code,
                m_name: data.doc_name,
                m_room: data.housedesc,
                m_type: data.doc_type,
                m_state: parseInt(data.doc_status),
            })
        })
    }

    //获取审批记录
    getRecord = (id) => {
        const that = this;
        axios.post(Api.rmApprovalOne,{
            docId: id,
            currentPage: that.state.m_current
        })
        .then(function(resp){
            const { data } = resp;
            if(data){
                const stepData = that.state.stepData;
                stepData[0].description = data.borrowUser;
                stepData[0].time = data.borrowDate ? data.borrowDate.substring(0,10) : '';
                stepData[1].description = data.auditingDept;
                stepData[1].time = data.auditingDate ?data.auditingDate.substring(0,10) : '';
                stepData[2].description = data.chargeDept;
                stepData[2].time = data.chargeDeptDate ? data.chargeDeptDate.substring(0,10) : '';
                stepData[3].description = data.chargePerson;
                stepData[3].time = data.chargePersonDate ? data.chargePersonDate.substring(0,10) : '';

                that.setState({
                    stepData: stepData
                })
            }
        })
    }

    //审批
    approval = () => {
        const that = this;
        if(that.state.openModalType == '查看'){
            that.setModalVisible(false);
        }else{
            this.props.form.validateFields((err,values)=>{
                if(!err){
                    axios.post(Api.rmApproval,{
                        docId: that.state.docIds
                    })
                    .then((function(resp){
                        const data = resp.data;
                        if(data.flag == '1'){
                            notification.destroy();
                            notification['success']({message:data.msg})
                            that.sendData()
                        }else{
                            notification.destroy();
                            notification['warning']({message:data.msg})
                        }
                        that.setModalVisible(false);
                    }))
                }
            })
        }
    }

    //驳回
    reject = () => {
        const that = this;
        this.props.form.validateFields((err,values)=>{
            if(!err){
                axios.post(Api.rmReject,{
                    docId: that.state.docIds
                })
                .then((function(resp){
                    const data = resp.data;
                    if(data.flag == '1'){
                        notification.destroy();
                        notification['success']({message:data.msg})
                        that.sendData()
                    }else{
                        notification.destroy();
                        notification['warning']({message:data.msg})
                    }
                    that.setModalVisible(false);
                }))
            }
        })
    }

    //归档
    pigeonhole = (item) => {
        const that = this;
        axios.post(Api.rmBack,{
            docId : item.doc_id
        })
        .then(function(resp){
            const data = resp.data;
            if(data.flag === '0'){
                notification.destroy();
                notification['warning']({message:data.msg});
            }else if(data.flag === '1'){
                notification.destroy();
                notification['success']({message:data.msg});
                that.sendData();
            }
            that.setModalVisible(false);
        })
    }

    render () {
        const { form : { getFieldDecorator }, currentUserLoading } = this.props;

        const columns = [
            {
                title: '档案名称',
                key: 'doc_name',
                dataIndex: 'doc_name',
            },
            {
                title: '档案位置',
                key: 'cabinetdesc',
                dataIndex: 'cabinetdesc',
            },
            {
                title: '档案柜所在房间',
                key: 'housedesc',
                dataIndex: 'housedesc',
            },
            {
                title: '档案状态',
                key: 'doc_status1',
                dataIndex: 'doc_status1',
            },
            {
                title: '档案类型',
                key: 'doc_type',
                dataIndex: 'doc_type',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) =>  {
                    return record.doc_status == "0" ? "-" :
                    (   
                        record.doc_status > 0 && record.doc_status < 4 ?
                        (
                            <span>
                                {Number(sessionStorage.getItem('isMap')) === 1 ?
                                    <a href="javascript:;" onClick={()=>this.openModal(record.doc_id,'审批',record.doc_status)}>
                                        审批
                                    </a> 
                                    :
                                    <a href="javascript:;" onClick={()=>this.openModal(record.doc_id,'查看')}>
                                        查看
                                    </a>
                                }
                            </span>
                        ) : (
                            <span>
                                {
                                    Number(sessionStorage.getItem('isMap')) === 1 ?
                                    <a href="javascript:;" onClick={()=>this.pigeonhole(record)}>
                                        归档
                                    </a>
                                    :
                                    <a href="javascript:;" onClick={()=>this.openModal(record.doc_id,'查看')}>
                                        查看
                                    </a>
                                }
                            </span>
                        )
                    )
                }
            },
        ]


        return (
            <PageHeaderWrapper loading={currentUserLoading}>
                <div className='mainContainer'>
                    <div className='contentHeader'>
                        <div className='contentHeaderTitle'>
                            <p>借取审批</p>
                            <p>BORROW APPROVAL</p>
                        </div>
                    </div>

                    <div className='pom'>
                        <div className='mrb15'>
                            <Form layout='inline' align='center' onSubmit={this.query}>
                                <FormItem label="档案名称：">
                                    {getFieldDecorator('s_name')(
                                        <Input placeholder="请输入档案名称"/>
                                    )}
                                </FormItem>
                                <FormItem label='档案状态：'>
                                    {getFieldDecorator('s_state')(
                                        <Select placeholder="请选择档案状态">
                                            <Option value="0">未借出</Option>
                                            <Option value="1">已借出</Option>
                                        </Select>
                                    )}
                                </FormItem>
                                <FormItem label='档案类型：'>
                                    {getFieldDecorator('s_type')(
                                        <Select placeholder="请选择档案类型">
                                            <Option value="0">核实情况报告</Option>
                                            <Option value="1">内部文档</Option>
                                            <Option value="2">划转通知</Option>
                                            <Option value="3">权属文件</Option>
                                        </Select>
                                    )}
                                </FormItem>
                                <Row gutter={24} style={{ textAlign: 'center'}}>
                                    <Button icon='search' type='primary' htmlType='submit'>搜索</Button>&emsp;
                                    <Button icon="reload" type="primary" htmlType='button' onClick={this.resetForm}>重置</Button>
                                </Row>
                            </Form>
                        </div>

                        <Table 
                            bordered={true}
                            scroll={{ x:true }}
                            columns={columns}
                            dataSource={this.state.tableData}
                            pagination={{
                                defaultPageSize:this.state.pageSize,
                                current:this.state.current,
                                total:this.state.totalSize,
                                onChange:this.pageChange,
                                showTotal: total => `共 ${total} 项`
                            }}/>
                    </div>

                    <Modal
                        title="借取审批"
                        centered
                        visible={this.state.modalVisible}
                        width={800}
                        onCancel = {() => this.setModalVisible(false)}
                        footer={
                            (this.state.docStatus>0 && this.state.docStatus<4) ?
                            [
                                <Button key="back" onClick={this.reject}>驳回</Button>,
                                <Button key="submit" type="primary" onClick={this.approval}>
                                同意
                                </Button>
                            ]
                            :
                            [
                                <Button key="back" onClick={() => this.setModalVisible(false)}>取消</Button>,
                                <Button key="submit" type="primary" onClick={() => this.setModalVisible(false)}>
                                确定
                                </Button>
                            ]
                        }
                    >
                        <div>
                            <Steps size="small" current={this.state.m_state}>
                                {this.state.stepData.map((item, index) => {
                                return (
                                    <Step
                                    // status={this.state.m_state}
                                    description={[
                                        <div key={index}>
                                        <p>{item.description}</p>
                                        <p>{item.time}</p>
                                        </div>,
                                    ]}
                                    title={item.title}
                                    key={index}
                                    />
                                );
                                })}
                            </Steps>
                            <Form layout='inline' style={{marginTop:'25px'}}>
                                <Row>
                                    <Col span={8}>
                                        <FormItem label='档案编号：'>{this.state.m_number}</FormItem>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem label='档案名称：'>{this.state.m_name}</FormItem>
                                    </Col>
                                    {/* <Col span={8}>
                                        <FormItem label='档案位置：'>{this.state.m_number}</FormItem>
                                    </Col> */}
                                    <Col span={8}>
                                        <FormItem label='所在房间：'>{this.state.m_room}</FormItem>
                                    </Col>
                                    <Col span={8}>
                                        <FormItem label='档案类型：'>{this.state.m_type}</FormItem>
                                    </Col>
                                </Row>  
                            </Form>
                        </div>
                    </Modal>
                </div>
            </PageHeaderWrapper>
        )
    }
}

const WrappedApp = Form.create()(BorrowApproval);

export default WrappedApp;
